package org.yx.service.sbas.save_base_material;

import com.xiaoleilu.hutool.util.StrUtil;
import org.springframework.util.StreamUtils;
import org.yx.exception.BizException;
import org.yx.models.SbasMatDef;
import org.yx.utils.BaseService;
import org.yx.utils.FieldMap;

/**
 * 保存物料信息（新增、修改或删除等）
 * @author zxw
 * @since 2018/03/27
**/
public class SbasSaveBaseMaterialService extends BaseService {
	public SbasSaveBaseMaterialOut saveBaseMaterial(SbasSaveBaseMaterialIn in) throws Exception {
		checkStringNotBlank(in, "matCode,matVer");
		SbasMatDef oldMat = selectWithPk(SbasMatDef.class, in.getUserOrgCode(), in.getMatCode(), in.getMatVer());
		if(StrUtil.isBlank(in.getFifoFlag())){
			in.setFifoFlag("N");
		}
		if(StrUtil.isBlank(in.getTraceFlag())){
			in.setTraceFlag("N");
		}

		SbasMatDef mat = new SbasMatDef();
		if (oldMat != null) {
			if (new Character('D').equals(oldMat.getMatStatus())) {
				throw new BizException("SBAS-0002", new FieldMap("matCode", oldMat.getMatCode()));
			}

			if (new Character('D').equals(in.getMatStatus())) {
				oldMat.setMatStatus(in.getMatStatus());

				update(oldMat, "matStatus");
			} else {
				copyProperties(oldMat, mat);
				copyProperties(in, mat);
				if (in.getMatStatus() == null) {
					mat.setMatStatus('N');
				}

				update(mat);
			}
		} else {
			copyProperties(in, mat);
			mat.setOrgCode(in.getUserOrgCode());
			mat.setMatStatus('N');

			insert(mat);
		}

		SbasSaveBaseMaterialOut out = new SbasSaveBaseMaterialOut();

		return out;
	}
}